﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BesAsm.Stormwater.HspfCore;

namespace BesAsm.Stormwater.HspfResults
{
  public class ResultsCombiner
  {
    private const double IN_AC_PER_DAY_TO_CFS = 0.042014;

    public ResultsCombiner()
    {
    }

    public List<CatchmentResultsCollection> MergeReaders(Wh2Reader wh2reader, L61Reader l61reader)
    {
      List<CatchmentResultsCollection> allCatchmentResults;
      allCatchmentResults = new List<CatchmentResultsCollection>();

      List<Catchment> catchments = wh2reader.Catchments;
      LandSegmentsCollection resultsCollection = l61reader.LandSegments;      

      foreach (Catchment catchment in catchments)
      {
        CatchmentResultsCollection crc = new CatchmentResultsCollection(catchment);
        allCatchmentResults.Add(crc);

        foreach (LandSegmentResults segResult in resultsCollection)
        {
          if (!catchment.Segments.Contains(segResult.SegmentNumber))
            continue;

          double segmentArea = catchment.Segments[segResult.SegmentNumber].Area;
          crc.Area += segmentArea;
          
          foreach (L61Block block in segResult)
          {
            CatchmentResult cr;
            if (!crc.Contains(block.ResultsDate))
            {
              cr = new CatchmentResult(block.ResultsDate);              
              crc.Add(cr);
            }
            else
              cr = crc[block.ResultsDate];

            double convFactor = segmentArea * IN_AC_PER_DAY_TO_CFS / DateTime.DaysInMonth(block.ResultsDate.Year, block.ResultsDate.Month);
            cr.Agwo += (block.Fluxes.Agwo * convFactor);
            cr.Ifwo += (block.Fluxes.Ifwo * convFactor);
            cr.Igwi += (block.Fluxes.Igwi * convFactor);
            cr.Pero += (block.Fluxes.Pero * convFactor);
            cr.Supy += (block.Fluxes.Supy * convFactor);
            cr.Suro += (block.Fluxes.Suro * convFactor);            
          }          
        }
      }
      return allCatchmentResults;
    }
  }
}
